/*
 * Help.java
 *
 * Created on 29 octobre 2007, 16:13
 */
package com.reimscopie.console ;

import java.io.* ;
import java.text.* ;
import java.util.* ;


/**
 * This is the shell help command. This command is always include in a
 * console instance.
 */
class Help extends Command {
  
  // all the commands
  private Map<String,Command> commands ;
  
  /**
   * Create a new <code>Help</code>.
   *
   * @param commands The referenced commands.
   */
  Help(Map<String,Command> commands) {
    
    this.commands = commands ;
    
  }

  
  /**
   * Return the name of this command. The name is the first word in the shell
   * command line.
   *
   * @return <code>"help"</code>.
   */
  public String getName() {
    return "help" ;
  }
  
  
  /**
   * Return a short help message about this command.
   *
   * @return The command help.
   */
  public String getHelp() {
    return "Display helpful information" ;
  }
  
  
  /**
   * Return the command usage. This string must give all command options with
   * a description for each option.
   *
   * @return The command usage.
   */
  public String getUsage() {
    return "help [command]" ;
  }
  
  
  /**
   * Execute this command.
   *
   * @param args The arguments given in the command line.
   * @param output The command output.
   */
  public void execute(String[] args,ConsoleOutput output) {
    
    // command list
    if (args == null  ||  args.length == 0)
      printList(output) ;
    
    // detail help
    else if (args.length == 1)
      printDetail(args[0],output) ;
    
    // error
    else {
      output.printError("usage: ") ;
      output.printError(getUsage(),true) ;
    }
    
  }
  
  
  /**
   * Print the command list.
   *
   * @param output The command output.
   */
  private void printList(ConsoleOutput output) {
  
    String[] names = new String[commands.size()] ;
    commands.keySet().toArray(names) ;

    Arrays.sort(names,Collator.getInstance()) ;

    output.print("Commands :",true) ;

    for (String name : names) {
      Command command = commands.get(name) ;
      output.print("  ") ;
      output.print(name) ;
      output.print('\t') ;
      output.print(command.getHelp(),true) ;
    }
  }
  
  
  /**
   * Print the help for the specified command.
   *
   * @param name The name of the target command.
   * @param output The command output.
   */
  private void printDetail(String name,ConsoleOutput output) {
  
    Command command = commands.get(name) ;
  
    // no such comand
    if (command == null) {
      output.printError("no such command: ") ;
      output.printError(name,true) ;
    }
    
    // help
    else {
      output.print(name) ;
      output.print(": ") ;
      output.print(command.getHelp(),true) ;

      output.print("usage: ") ;
      output.print(command.getUsage(),true) ;
    }
    
  }
  
}
